import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core';
import { WebGLService } from 'src/app/services/webgl.service';

@Component({
    selector: 'texture-rect',
    templateUrl: './texture-rect.component.html',
    styleUrls: ['./texture-rect.component.scss']
})
export class TextureRectComponent implements OnInit, AfterViewInit, OnDestroy {
    private vertexShaderSource = `
        attribute vec4 a_Position;
        attribute vec2 a_TexCoord;
        varying vec2 v_TexCoord;
        void main () {
            gl_Position = a_Position;
            v_TexCoord = a_TexCoord;
        } 
    `;
    private fragShaderSource = `
        #ifdef GL_ES
        precision mediump float;
        #endif

        uniform sampler2D u_Sampler;
        varying vec2 v_TexCoord;
        void main () {
            gl_FragColor = texture2D(u_Sampler, v_TexCoord);
        }
    `;
    private gl: WebGLRenderingContext;
    constructor(private webglService: WebGLService) { }
    ngOnInit() { }
    ngAfterViewInit () {
        this.init();
    }
    ngOnDestroy () {}

    private init () {
        const canvas = document.querySelector('#myCanvas') as HTMLCanvasElement;
        this.gl = canvas.getContext('webgl');
        // 初始化 shader
        this.webglService.initShader(this.gl, this.vertexShaderSource, this.fragShaderSource);

        const n = this.initVertexBuffer(this.gl);

        this.gl.clearColor(0.0, 0.0, 0.0, 1.0);

        this.initTexture(this.gl, n);
    }
    private initVertexBuffer (gl: WebGLRenderingContext) {
        const vertices = new Float32Array([
            //x     y   texture:x   y
           -0.5,    0.5,    -0.3,   1.7,
            0.5,    0.5,    1.7,    1.7,
           -0.5,   -0.5,    -0.3,   -0.2,
            0.5,   -0.5,    1.7,    -0.2
        ]);
        const n = 4;    // 点的个数
        const byteLen = vertices.BYTES_PER_ELEMENT;

        // 创建缓冲区对象
        const vertexTexCoordBuffer = gl.createBuffer();
        
        // 将缓冲区对象绑定到目标
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexTexCoordBuffer);

        // 向缓冲区对象中写入数据
        gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

        const program = this.webglService.getProgramByGLContext(gl);
        const a_Position = gl.getAttribLocation(program, 'a_Position');
        const a_TexCoord = gl.getAttribLocation(program, 'a_TexCoord');

        // 将缓冲区对象分配给 a_Position 变量
        gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 4 * byteLen, 0);
        gl.vertexAttribPointer(a_TexCoord, 2, gl.FLOAT, false, 4 * byteLen, 2 * byteLen);

        // 连接 a_Position 变量与分配给它的缓冲区对象
        gl.enableVertexAttribArray(a_Position);
        gl.enableVertexAttribArray(a_TexCoord);

        return n;
    }

    private initTexture (gl: WebGLRenderingContext, n: number) {
        const texture = gl.createTexture();

        const program = this.webglService.getProgramByGLContext(gl);
        const u_Sampler = gl.getUniformLocation(program, 'u_Sampler');

        const image = new Image();
        image.src = '/assets/img/blueflower2.JPG';
        image.addEventListener('load', () => {
            this.loadTexture(gl, n, texture, image, u_Sampler);
        });
    }

    private loadTexture (gl:WebGLRenderingContext, n: number, texture: WebGLTexture, image: HTMLImageElement, location: WebGLUniformLocation) {
        // 对纹理图像进行Y轴反转
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1); 
        // 激活纹理单元，开启0号纹理单元
        gl.activeTexture(gl.TEXTURE0);
        // 绑定纹理对象
        gl.bindTexture(gl.TEXTURE_2D, texture);
      
        // 设置纹理参数
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        // Set the texture image
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);
        
        // Set the texture unit 0 to the sampler
        gl.uniform1i(location, 0);
        
        gl.clear(gl.COLOR_BUFFER_BIT);   // Clear <canvas>
      
        gl.drawArrays(gl.TRIANGLE_STRIP, 0, n); // Draw the rectangle
    }
}